package com.example.return3.service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName:MessageService
 * Package:com.example.ttl1.service
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/11-21:30
 * @Version:v1.0
 */
@Service
@Slf4j
public class MessageService{

    @Resource
    private RabbitTemplate rabbitTemplate;


    @Value("${my.exchangeName}")
    private String exchangeName;

    @PostConstruct
    public void init() {
        //设置回调函数
        rabbitTemplate.setReturnsCallback(
                new RabbitTemplate.ReturnsCallback() {
                    @Override
                    public void returnedMessage(ReturnedMessage returned) {
                        log.error("消息从交换机没有正确的路由到(投递到)队列,原因为:{}",returned.getReplyText());
                    }
                }
        );
    }

    public void sendMsg() {

        Message message = MessageBuilder.withBody("过期时间TTL".getBytes()).build();

        rabbitTemplate.convertAndSend(exchangeName , "info", message);

        log.info("消息发送完毕,发送时间为:{}", new Date());
    }

}
